#include <stdio.h>
#include <lame.h>
#include <jni.h>
#include <android/log.h>

#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "JNI_DEBUGGING", __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,   "JNI_DEBUGGING", __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,    "JNI_DEBUGGING", __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN,    "JNI_DEBUGGING", __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,   "JNI_DEBUGGING", __VA_ARGS__)



jstring Java_com_my_mp3_LameWrapper_createMP3File( JNIEnv* env,
                                                  jobject thiz)
{
	int read, write;

    FILE *pcm = fopen("/mnt/sdcard/a.wav", "rb");
    FILE *mp3 = fopen("/mnt/sdcard/file.mp3", "wb");
	
	LOGI("INIT");
    const int PCM_SIZE = 8192;
    const int MP3_SIZE = 8192;

    short int pcm_buffer[PCM_SIZE*2];
    unsigned char mp3_buffer[MP3_SIZE];
LOGI("INIT1");
    lame_t lame = lame_init();
    lame_set_in_samplerate(lame, 44100);
    lame_set_VBR(lame, vbr_default);
    lame_init_params(lame);
	LOGI("INIT2");
    do {
        read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
		LOGI("read: "+read);
        if (read == 0)
            write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
        else
            write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
        fwrite(mp3_buffer, write, 1, mp3);
    } while (read != 0);
LOGI("INIT3");
    lame_close(lame);
    fclose(mp3);
    fclose(pcm);
	
    return (*env)->NewStringUTF(env, "true");

}

